import requests, time
import hashlib, re, urllib


class Youdaofanyi():
    def __init__(self):
        # self.input = input("请输入要翻译的内容：")
        self.sign1 = None
        self.input = "i love you"
        # self.input = "+".join(self.input.split(" "))
        self.t1 = "yU5nT5dK3eZ1pI4j"
        self.webkey = "webfanyi-key-getter-2025"
        self.headers = {
            'Accept': 'application/json, text/plain, */*',
            'Accept-Language': 'zh-CN,zh;q=0.9',
            'Cache-Control': 'no-cache',
            'Connection': 'keep-alive',
            'Content-Type': 'application/x-www-form-urlencoded',
            'Origin': 'https://fanyi.youdao.com',
            'Pragma': 'no-cache',
            'Referer': 'https://fanyi.youdao.com/',
            'Sec-Fetch-Dest': 'empty',
            'Sec-Fetch-Mode': 'cors',
            'Sec-Fetch-Site': 'same-site',
            'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/140.0.0.0 Safari/537.36',
            'sec-ch-ua': '"Chromium";v="140", "Not=A?Brand";v="24", "Google Chrome";v="140"',
            'sec-ch-ua-mobile': '?0',
            'sec-ch-ua-platform': '"Windows"',
            # 'Cookie': 'OUTFOX_SEARCH_USER_ID=-500924075@5.34.216.83; OUTFOX_SEARCH_USER_ID_NCOO=1083037631.7095604; DICT_DOCTRANS_SESSION_ID=OGUyM2FkZjAtODQyMi00ZDlhLWE2NGItNzExYmE4NzM5MjYw; _uetsid=8382e6f08df611f0be57fd2003cef265; _uetvid=8973cef08a2911f094cc69659c84a9b3',
        }

    def url_encode(self, text: str) -> str:
        """把普通字符串编码为 URL 格式"""
        return urllib.parse.quote(text)

    def url_decode(self, encoded_str: str) -> str:
        """解码 URL 编码的字符串"""
        return urllib.parse.unquote(encoded_str)

    def get_ms_timestamp(self):
        timestamp = str(time.time() * 1000).split(".")[0]
        return timestamp

    def md5(self, e: str) -> str:
        """等价于 JS 里的 md5(digest('hex'))"""
        self.sign1 = hashlib.md5(e.encode("utf-8")).hexdigest()
        return self.sign1

    def parse_sign1(self) -> str:
        """生成 sign1"""
        raw = f"client=fanyideskweb&mysticTime={self.get_ms_timestamp()}&product=webfanyi&key={self.t1}"
        return self.md5(raw)

    def get_key(self):
        params = {
            "keyid": "webfanyi-key-getter-2025",
            "sign": self.parse_sign1(),
            "client": "fanyideskweb",
            "product": "webfanyi",
            "appVersion": "1.0.0",
            "vendor": "web",
            "pointParam": "client,mysticTime,product",
            "mysticTime": self.get_ms_timestamp(),
            "keyfrom": "fanyi.web",
            "mid": "1",
            "screen": "1",
            "model": "1",
            "network": "wifi",
            "abtest": "0",
            "yduuid": "abcdefg"
        }
        response = requests.get(
            'https://dict.youdao.com/webtranslate/key',
            params=params,
            headers=self.headers,
        ).json()
        return response

    def parse_sign2(self):
        """生成 sign2"""
        secretKey = self.get_key()['data']['secretKey']
        raw = f"client=fanyideskweb&mysticTime={self.get_ms_timestamp()}&product=webfanyi&key={secretKey}"
        return self.md5(raw)

    def detect_lang(self, text: str) -> str:
        """检测语言：如果有中文 → 目标设为英文，否则设为中文"""
        if re.search(r'[\u4e00-\u9fff]', text):  # 匹配中文范围
            return "en"
        else:
            return "zh-CHS"

    def parse_fanyi(self):
        url = "https://dict.youdao.com/webtranslate"
        mysticTime = self.get_ms_timestamp()

        # 自动检测目标语言
        target_lang = self.detect_lang(self.input)

        sign = self.parse_sign2()
        
        data = {
            'i': self.input,
            'from': target_lang,
            'to': '',
            'useTerm': 'false',
            'dictResult': 'true',
            'keyid': 'webfanyi',
            'sign': sign,
            'client': 'fanyideskweb',
            'product': 'webfanyi',
            'appVersion': '1.0.0',
            'vendor': 'web',
            'pointParam': 'client,mysticTime,product',
            'mysticTime': mysticTime,
            'keyfrom': 'fanyi.web',
            'mid': '1',
            'screen': '1',
            'model': '1',
            'network': 'wifi',
            'abtest': '0',
            'yduuid': 'abcdefg',
        }

        response = requests.post(url, headers=self.headers, data=data)
        print(response.text)


if __name__ == '__main__':
    youdaofanyi = Youdaofanyi()
    print("sign1: " + youdaofanyi.parse_sign1())
    print("get_key: ", end="")
    print(youdaofanyi.get_key())
    print("sign2: " + youdaofanyi.parse_sign2())
    youdaofanyi.parse_fanyi()
    print("===========================")
    encode = youdaofanyi.url_encode(youdaofanyi.input)
    decode = youdaofanyi.url_decode(encode)
    print(f"url编码: {encode}")
    print(f"url解码: {decode}")
